<template>
    <view class="qiang-page">
      <!-- 顶部导航栏 -->
      <uni-nav-bar 
        :border="false"
        background-color="#ffffff"
        color="#333333"
        title="抢单大厅"
        left-icon="left"
        @clickLeft="goBack"
      >
        <template #right>
          <view class="nav-right">
            <text class="nav-icon">•••</text>
            <text class="nav-icon">−</text>
            <text class="nav-icon">⊙</text>
          </view>
        </template>
      </uni-nav-bar>
  
      <!-- 订单类型切换 -->
      <view class="order-type-tabs">
        <view 
          class="tab-item"
          :class="{ active: activeTab === 'delivery' }"
          @click="switchTab('delivery')"
        >
          外送单
          <view class="badge" v-if="getOrderCount('delivery') > 0">{{ getOrderCount('delivery') }}</view>
        </view>
        <view 
          class="tab-item"
          :class="{ active: activeTab === 'errand' }"
          @click="switchTab('errand')"
                >
         跑腿单
          <view class="badge" v-if="getOrderCount('errand') > 0">{{ getOrderCount('errand') }}</view>
        </view>
      </view>
  
      <!-- 主要内容区域 -->
      <view class="main-content">
        <!-- 左侧时间段选择 -->
        <view class="time-sidebar">
          <view 
            class="time-item"
            :class="{ active: selectedTime === 'all' }"
            @click="selectTime('all')"
          >
            预约
            <view class="green-dot" v-if="selectedTime === 'all'"></view>
          </view>
          <view 
            class="time-item today-all"
            :class="{ active: selectedTime === 'today' }"
            @click="selectTime('today')"
          >
            今日全部
            <view class="green-dot" v-if="selectedTime === 'today'"></view>
          </view>
          
          <view 
            v-for="timeSlot in timeSlots"
            :key="timeSlot.value"
            class="time-item"
            :class="{ active: selectedTime === timeSlot.value }"
            @click="selectTime(timeSlot.value)"
          >
            {{ timeSlot.label }}
            <view class="green-dot" v-if="hasOrdersInSlot(timeSlot.value)"></view>
          </view>
        </view>
  

        
        <!-- 右侧订单列表 -->
        <view class="order-list">
          <!-- 有订单时显示订单列表 -->
          <view 
            v-for="order in filteredOrders"
            :key="order.id"
            class="order-card"
            @click="viewOrderDetail(order.id)"
          >
            <view class="order-header">
              <text class="order-title">{{ order.title }}</text>
              <text class="order-time">{{ order.time }}</text>
              <text class="wait-label" :class="order.type === 'delivery' ? 'delivery-label' : 'errand-label'">
                {{ order.type === 'delivery' ? '外送单' : '跑腿单' }}
              </text>
            </view>
            
            <view class="order-content">
              <view class="location-info">
                <view class="location-item">
                  <view class="location-dot blue"></view>
                  <text class="location-text">{{ order.pickup }}</text>
                </view>
                <view class="location-item">
                  <view class="location-dot red"></view>
                  <text class="location-text">{{ order.delivery }}</text>
                  <text class="price">¥{{ order.price }}</text>
                </view>
                <view class="order-type-info">
                  <text class="type-icon">{{ order.type === 'delivery' ? '🍔' : '📦' }}</text>
                  <text class="type-text">{{ order.type === 'delivery' ? '外送服务' : '跑腿服务' }}</text>
                </view>
              </view>
              
              <view class="order-actions">
                <button class="grab-btn" @click.stop="grabOrder(order.id)">
                  抢单
                </button>
              </view>
            </view>
          </view>
          
          <!-- 无订单时显示空状态 -->
          <view v-if="filteredOrders.length === 0" class="empty-state">
            <view class="empty-icon">📦</view>
            <text class="empty-title">暂无{{ activeTab === 'delivery' ? '外送' : '跑腿' }}订单</text>
            <text class="empty-desc">新订单会在这里显示，请稍后再来看看</text>
          </view>
        </view>
      </view>
  
      <!-- 底部导航栏 -->
      <view class="bottom-nav">
        <view class="nav-item active">
          <image src="/static/images/icon/main_ea9518.png" class="nav-icon"></image>
          <text class="nav-text">抢单大厅</text>
        </view>
        <view class="nav-item" @click="goToMyOrders">
          <image src="/static/images/icon/my.png" class="nav-icon"></image>
          <text class="nav-text">我的接单</text>
        </view>

      </view>
  
      <!-- 悬浮按钮 -->
      <view 
        class="floating-button"
        :class="{ dragging: floatingBtn.isDragging }"
        :style="{
          transform: floatingBtn.isDragging 
            ? `translate(${floatingBtn.x}px, ${floatingBtn.y}px) scale(1.05)` 
            : `translate(${floatingBtn.x}px, ${floatingBtn.y}px)`,
          transition: floatingBtn.isDragging ? 'none' : 'transform 0.3s ease'
        }"
        @touchstart="onFloatingTouchStart"
        @touchmove="onFloatingTouchMove"
        @touchend="onFloatingTouchEnd"
        @click="handleFloatingClick"
      >
       
        <text class="sub-text">历史接单</text>
      </view>
    </view>
  </template>
  
  <script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { requestUrl } from '@/config'

// 声明uni全局变量
declare const uni: any
  
  // 类型定义
  interface Order {
    id: number
    title: string
    time: string
    pickup: string
    delivery: string
    price: string
    timeSlot: string
    type: 'delivery' | 'errand'
  }
  
  interface TimeSlot {
    label: string
    value: string
  }
  
  // 响应式数据
  const activeTab = ref('errand') // 当前选中的标签页
  const selectedTime = ref('today') // 当前选中的时间段
  
  // 悬浮球状态
  const floatingBtn = ref({
    x: 320, // 初始X位置
    y: 400, // 初始Y位置
    isDragging: false,
    startX: 0,
    startY: 0,
    initialX: 0,
    initialY: 0
  })
  
  // 时间段配置
  const timeSlots = ref<TimeSlot[]>([
    { label: '05:00-07:00', value: '05-07' },
    { label: '07:00-09:00', value: '07-09' },
    { label: '09:00-11:00', value: '09-11' },
    { label: '11:00-13:00', value: '11-13' },
    { label: '13:00-16:00', value: '13-16' },
    { label: '15:00-17:00', value: '15-17' },
    { label: '17:00-19:00', value: '17-19' },
    { label: '19:00-21:00', value: '19-21' },
    { label: '21:00-23:00', value: '21-23' },
    { label: '23:00-00:00', value: '23-00' }
    
  ])
  
  // 订单数据
  const orders = ref<Order[]>([])
  const loading = ref(false)
  
  // 计算属性：过滤后的订单
  const filteredOrders = computed(() => {
    return orders.value.filter((order: Order) => {
      // 根据当前选中的标签页过滤
      if (order.type !== activeTab.value) return false
      
      // 根据时间段过滤
      if (selectedTime.value === 'all' || selectedTime.value === 'today') {
        return true
      }
      
      return order.timeSlot === selectedTime.value
    })
  })
  
  // 方法
  const goBack = () => {
    uni.navigateBack()
  }
  
  const switchTab = (tab: string) => {
    activeTab.value = tab
  }
  
  const selectTime = (time: string) => {
    selectedTime.value = time
  }
  
  const hasOrdersInSlot = (timeSlot: string): boolean => {
    return orders.value.some((order: Order) => 
      order.timeSlot === timeSlot && order.type === activeTab.value
    )
  }

  // 获取指定类型的订单数量
  const getOrderCount = (type: 'delivery' | 'errand'): number => {
    return orders.value.filter(order => order.type === type).length
  }
  
  const grabOrder = (orderId: number) => {
    // 直接跳转到详情页面，由详情页面处理抢单逻辑
    viewOrderDetail(orderId)
  }

  // 添加订单到我的接单列表（使用 Axios + config.ts）
  const addToMyOrders = async (order: Order) => {
    try {
      // 获取用户ID（这里先用模拟的用户ID）
      const userId = uni.getStorageSync('userId') || 'user_' + Date.now()
      if (!uni.getStorageSync('userId')) {
        uni.setStorageSync('userId', userId)
      }
      
      // 使用 Axios 和 config.ts 中的 requestUrl - 统一数据格式
      const requestData = {
        orderId: String(order.id), // String类型，与数据库一致
        userId: String(userId), // String类型，必需
        title: String(order.title || '未知订单'), // String类型，必需
        pickup: String(order.pickup || ''), // String类型，必需
        delivery: String(order.delivery || ''), // String类型，必需
        price: String(order.price || '0.00'), // String类型，必需
        serviceType: order.type === 'delivery' ? 'takeout' : 'express', // 枚举值，必需
        originalOrder: {
          timeSlot: order.timeSlot,
          type: order.type,
          time: order.time
        }
      }
      
      console.log('抢单页面 - 准备发送的请求数据:', requestData)
      
      const response = await axios.post(`${requestUrl}/jjk/myOrders/add`, requestData, {
        headers: {
          'Content-Type': 'application/json'
        },
        timeout: 10000
      })
      
      console.log('抢单API响应:', response.data)
      if (response.data.success) {
        console.log('订单保存到数据库成功')
        
        // 同时保存到本地存储作为备用
        saveToLocalStorage(order)
        
        uni.showToast({
          title: '抢单成功！',
          icon: 'success'
        })
        
        // 延迟跳转到我的接单页面
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/JJK/my-orders'
          })
        }, 1500)
      } else {
        console.error('订单保存失败:', response.data.message)
        uni.showToast({
          title: response.data.message || '保存失败',
          icon: 'error'
        })
        // 如果后端保存失败，可以fallback到本地存储
        saveToLocalStorage(order)
      }
    } catch (error) {
      console.error('调用后端API失败:', error)
      // 网络错误时fallback到本地存储
      saveToLocalStorage(order)
      
      uni.showToast({
        title: '网络错误，已保存到本地',
        icon: 'none'
      })
    }
  }
  
  // 本地存储备用方案
  const saveToLocalStorage = (order: Order) => {
    const myOrders = uni.getStorageSync('myOrders') || '[]'
    const myOrdersList = JSON.parse(myOrders)
    
    const newMyOrder = {
      id: order.id,
      title: order.title,
      pickup: order.pickup,
      delivery: order.delivery,
      price: order.price,
      status: 'ongoing',
      acceptTime: new Date().toLocaleString(),
      serviceType: order.type === 'delivery' ? 'takeout' : 'express'
    }
    
    myOrdersList.unshift(newMyOrder)
    uni.setStorageSync('myOrders', JSON.stringify(myOrdersList))
    
    console.log('订单已保存到本地存储:', newMyOrder)
  }
  
  const showQR = () => {
    uni.showToast({
      title: '显示历史接单',
      icon: 'none'
    })
  }

  const viewOrderDetail = (orderId: number) => {
    // 将订单数据存储到本地存储，供抢单详情页面读取
    const order = orders.value.find(o => o.id === orderId)
    if (order) {
      uni.setStorageSync('grabOrderDetail', JSON.stringify(order))
    }
    
    // 跳转到抢单专门的详情页面
    uni.navigateTo({
      url: `/pages/JJK/grab-order-detail?id=${orderId}`
    })
  }

  const goToMyOrders = () => {
    uni.navigateTo({
      url: '/pages/JJK/my-orders'
    })
  }
  


  // 悬浮球触摸事件处理
  const onFloatingTouchStart = (e: any) => {
    const touch = e.touches[0]
    floatingBtn.value.isDragging = false
    floatingBtn.value.startX = touch.pageX
    floatingBtn.value.startY = touch.pageY
    floatingBtn.value.initialX = floatingBtn.value.x
    floatingBtn.value.initialY = floatingBtn.value.y
  }

  const onFloatingTouchMove = (e: any) => {
    e.preventDefault()
    const touch = e.touches[0]
    const deltaX = touch.pageX - floatingBtn.value.startX
    const deltaY = touch.pageY - floatingBtn.value.startY
    
    // 如果移动距离超过阈值，标记为拖拽状态
    if (Math.abs(deltaX) > 5 || Math.abs(deltaY) > 5) {
      floatingBtn.value.isDragging = true
    }
    
    if (floatingBtn.value.isDragging) {
      // 计算新位置
      let newX = floatingBtn.value.initialX + deltaX
      let newY = floatingBtn.value.initialY + deltaY
      
      // 获取屏幕尺寸进行边界限制
      try {
        const screenWidth = uni.getSystemInfoSync().windowWidth
        const screenHeight = uni.getSystemInfoSync().windowHeight
        const btnSize = 50
        
        // 边界限制
        newX = Math.max(0, Math.min(screenWidth - btnSize, newX))
        newY = Math.max(50, Math.min(screenHeight - btnSize - 100, newY))
        
        floatingBtn.value.x = newX
        floatingBtn.value.y = newY
      } catch (error) {
        console.error('获取屏幕信息失败:', error)
      }
    }
  }

  const onFloatingTouchEnd = () => {
    // 延迟重置拖拽状态，防止点击事件立即触发
    setTimeout(() => {
      floatingBtn.value.isDragging = false
    }, 100)
  }

  const handleFloatingClick = () => {
    // 只有在非拖拽状态下才触发点击事件
    if (!floatingBtn.value.isDragging) {
      showQR()
    }
  }

  // 获取订单数据
  const loadOrders = async () => {
    loading.value = true
    try {
      // 这里应该调用后端API获取订单数据
      // const response = await uni.request({
      //   url: 'http://localhost:3005/api/orders',
      //   method: 'GET'
      // })
      // orders.value = response.data.data
      
      // 生成测试数据
      const testOrders: Order[] = [
        {
          id: 1,
          title: '快递代取【宿舍楼A栋】',
          time: '今日 12:30',
          pickup: '西院快递点',
          delivery: '宿舍楼A栋',
          price: '7',
          timeSlot: '11-13',
          type: 'errand'
        },
        {
          id: 2,
          title: '帮拿外卖【黄焖鸡米饭】',
          time: '今日 18:00',
          pickup: '黄焖鸡米饭店',
          delivery: '教学楼1号',
          price: '5',
          timeSlot: '17-19',
          type: 'delivery'
        },
        {
          id: 3,
          title: '快递代取【图书馆】',
          time: '今日 14:00',
          pickup: '东院快递点',
          delivery: '图书馆',
          price: '6',
          timeSlot: '13-16',
          type: 'errand'
        },
        {
          id: 4,
          title: '帮拿外卖【麻辣烫】',
          time: '今日 19:30',
          pickup: '麻辣烫店',
          delivery: '宿舍楼B栋',
          price: '6',
          timeSlot: '19-21',
          type: 'delivery'
        },
        {
          id: 5,
          title: '快递代取【食堂】',
          time: '今日 16:00',
          pickup: '西院快递点',
          delivery: '食堂',
          price: '8',
          timeSlot: '15-17',
          type: 'errand'
        }
      ]
      
      orders.value = testOrders
      
      console.log('测试订单数据已加载:', orders.value)
    } catch (error) {
      console.error('加载订单失败:', error)
      uni.showToast({
        title: '加载失败，请重试',
        icon: 'error'
      })
    } finally {
      loading.value = false
    }
  }

  // 页面挂载时加载数据
  onMounted(() => {
    loadOrders()
  })
  </script>
  
  <style lang="scss" scoped>
  .qiang-page {
    height: 100vh;
    background-color: #f5f5f5;
    display: flex;
    flex-direction: column;
  }
  
  .nav-right {
    display: flex;
    gap: 10px;
    
    .nav-icon {
      font-size: 18px;
      color: #666;
    }
  }
  
  .order-type-tabs {
    display: flex;
    background-color: #fff;
    padding: 10px 20px;
    
    .tab-item {
      flex: 1;
      text-align: center;
      padding: 8px 16px;
      border-radius: 20px;
      position: relative;
      color: #666;
      
      &.active {
        background-color: #ff6b4a;
        color: #fff;
      }
      
      .badge {
        position: absolute;
        top: -5px;
        right: 10px;
        background-color: #ff4444;
        color: #fff;
        border-radius: 50%;
        width: 18px;
        height: 18px;
        font-size: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
  
  .main-content {
    flex: 1;
    display: flex;
    overflow: hidden;
  }
  
  .time-sidebar {
    width: 120px;
    background-color: #fff;
    border-right: 1px solid #eee;
    
    .time-item {
      padding: 15px 10px;
      text-align: center;
      border-bottom: 1px solid #f0f0f0;
      position: relative;
      font-size: 14px;
      color: #666;
      
      &.active {
        background-color: #fff0ee;
        color: #ff6b4a;
      }
      
      &.today-all {
        background-color: #ff6b4a;
        color: #fff;
      }
      
      .green-dot {
        position: absolute;
        right: 8px;
        top: 50%;
        transform: translateY(-50%);
        width: 6px;
        height: 6px;
        background-color: #4caf50;
        border-radius: 50%;
      }
    }
  }
  
  .order-list {
    flex: 1;
    padding: 10px;
    overflow-y: auto;
  }
  
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    text-align: center;
    
    .empty-icon {
      font-size: 48px;
      margin-bottom: 16px;
      opacity: 0.6;
    }
    
    .empty-title {
      font-size: 16px;
      color: #666;
      margin-bottom: 8px;
      font-weight: 500;
    }
    
    .empty-desc {
      font-size: 14px;
      color: #999;
      line-height: 1.4;
    }
  }
  
  .order-card {
    background-color: #fff;
    border-radius: 8px;
    margin-bottom: 10px;
    padding: 15px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    
    .order-header {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      
      .order-title {
        font-size: 16px;
        font-weight: bold;
        color: #333;
        margin-right: auto;
      }
      
      .order-time {
        font-size: 12px;
        color: #999;
        margin-right: 10px;
      }
      
      .wait-label {
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 12px;
        
        &.delivery-label {
          background-color: #e3f2fd;
          color: #1976d2;
        }
        
        &.errand-label {
          background-color: #fff3e0;
          color: #ff8f00;
        }
      }
    }
    
    .order-content {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
    }
    
    .location-info {
      flex: 1;
      
      .location-item {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        
        .location-dot {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          margin-right: 8px;
          
          &.blue {
            background-color: #2196f3;
          }
          
          &.red {
            background-color: #f44336;
          }
        }
        
        .location-text {
          flex: 1;
          font-size: 14px;
          color: #666;
        }
        
        .price {
          font-size: 16px;
          font-weight: bold;
          color: #f44336;
          margin-left: 10px;
        }
        
        .order-type-info {
          display: flex;
          align-items: center;
          margin-top: 8px;
          
          .type-icon {
            font-size: 16px;
            margin-right: 6px;
          }
          
          .type-text {
            font-size: 12px;
            color: #666;
          }
        }
      }
    }
    
    .order-actions {
      .grab-btn {
        background-color: #ff6b4a;
        color: #fff;
        border: none;
        border-radius: 20px;
        padding: 8px 20px;
        font-size: 14px;
      }
    }
  }
  
  .bottom-nav {
    display: flex;
    background-color: #fff;
    border-top: 1px solid #eee;
    padding: 10px 0;
    
    .nav-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .nav-icon {
        width: 24px;
        height: 24px;
        margin-bottom: 4px;
      }
      
      .nav-text {
        font-size: 12px;
        color: #999;
      }
      
      &.active .nav-text {
        color: #ff6b4a;
      }
    }
  }
  
  .floating-button {
    position: fixed;
    top: 0;
    left: 0;
    width: 50px;
    height: 50px;
    background-color: #ff6b4a;
    border-radius: 50%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-weight: bold;
    box-shadow: 0 4px 8px rgba(255, 107, 74, 0.3);
    z-index: 9999;
    user-select: none;
    cursor: pointer;
    
    &:active:not(.dragging) {
      transform: scale(0.95);
    }
    
    &.dragging {
      box-shadow: 0 8px 16px rgba(255, 107, 74, 0.5);
      opacity: 0.9;
    }
    
    .main-text {
      font-size: 14px;
      line-height: 1;
    }
    
    .sub-text {
      font-size: 10px;
      margin-top: -2px;
      line-height: 1;
    }
  }

  </style>
  